package com.efounder.form.comp.shoppingshow;

import androidx.recyclerview.widget.RecyclerView;

import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.efounder.builder.base.data.EFDataSet;
import com.efounder.builder.base.data.EFRowSet;
import com.efounder.builder.base.data.ESPRowSet;
import com.efounder.form.base.DataComponent;
import com.efounder.form.comp.FormCheckBox;
import com.efounder.form.comp.FormImage;
import com.efounder.form.comp.FormLabel;
import com.efounder.form.comp.FormSpinner;
import com.efounder.form.comp.FormTextInput;
import com.efounder.form.comp.shoppingcar.ItemSlideHelper;
import com.efounder.form.comp.shoppingcar.ShoppingCarDataManager;
import com.efounder.form.model.Column;
import com.efounder.form.model.JSONFormModel;
import com.efounder.frame.arcmenu.ArcMenu;
import com.efounder.frame.widget.EFArcMenuSuperScriptItem;
import com.efounder.mobilecomps.R;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by XinQing on 2016/9/13.
 * 第三步: 实例化上述定义的实体类,根据自己的需要可以实例化一个或多个，并将它们添加到List集合当中;
 第四步: 定义自己Adapter并集成BaseAdapter, 重写其中的方法。这是最关键的一步，也是难度最大的一步, 具体示例代码及其注释(不要着急，请细细看其中的注释)如下：

 */

public class ShoppingShowCategoryAdapter extends RecyclerView.Adapter implements  ItemSlideHelper.Callback{
    private RecyclerView mRecyclerView;
    // 标题类型
    private static final int TYPE_CATEGORY_ITEM = 0;
    // 子项类型
    private static final int TYPE_ITEM = 1;
    // 类别集合
    private List<EFDataSet> dataSetList;
    // 布局填充器
    private LayoutInflater mInflater;

    private ShoppingShow shoppingShow;

    public ShoppingShowCategoryAdapter(ShoppingShow shoppingShow) {
        this.shoppingShow = shoppingShow;
        mInflater = LayoutInflater.from(shoppingShow.getContext());
        dataSetList = new ArrayList<>();
        reloadData();
    }

    public void reloadData(){
        JSONFormModel formModel = (JSONFormModel) shoppingShow.getDataSetComponent();
        if (formModel == null || formModel.getFormDataModel() == null || formModel.getFormDataModel().getBillDataSet() == null) return;
        dataSetList.clear();
//        Map<String, EFDataSet> dataSetMap = formModel.getFormDataModel().getDataSetMap();
        EFRowSet billRowSet = (EFRowSet) formModel.getFormDataModel().getBillDataSet().getRowSetList().get(0);
        Map<String, EFDataSet> dataSetMap = billRowSet.getDataSetMap();
        if (dataSetMap == null) return;
        dataSetList.add(dataSetMap.get(shoppingShow.getDataSetID()));
        notifyDataSetChanged();
    }

    /**
     * 获取Item
     */
    public Object getItem(int position) {
        // 异常情况处理
        if (null == dataSetList || position < 0 || position > getItemCount()) {
            return null;
        }
        // 同一分类内，第一个元素的索引值
        int categroyFirstIndex = 0;
        for (EFDataSet dataSet : dataSetList) {
            int size = ShoppingCarDataManager.getItemCount(dataSet);
            // 在当前分类中的索引值
            int categoryIndex = position - categroyFirstIndex;
            // item在当前分类内
            if (categoryIndex < size) {
                return ShoppingCarDataManager.getItem(dataSet,categoryIndex);
            }
            // 索引移动到当前分类结尾，即下一个分类第一个元素索引
            categroyFirstIndex += size;
        }
        return null;
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = null;
        RecyclerView.ViewHolder holder = null;
        //获取指定位置的Item的类型
        switch (viewType) {
            //如果是标题类型, 则填充标题布局
            case TYPE_CATEGORY_ITEM:
                view = mInflater.inflate(R.layout.category_recyclerview_item_header, parent, false);
                if (!shoppingShow.isShowHeaderItem()){
                    ViewGroup.LayoutParams params = view.getLayoutParams();
                    params.height = 0;
                    params.width = 0;
                    view.setLayoutParams(params);
                }
                holder = new HeaderViewHolder(view);
                break;
            //如果是子项类型则填充子项的布局
            case TYPE_ITEM:
                view = LayoutInflater.from(parent.getContext()).inflate(R.layout.category_recyclerview_item, parent, false);
                holder = new ItemViewHolder(view);
                break;
        }
        return holder;
    }

    @Override
    public void onBindViewHolder(final RecyclerView.ViewHolder holder, final int position) {
        switch (holder.getItemViewType()){
            //如果是标题类型, 处理标题布局
            case TYPE_CATEGORY_ITEM:
                final HeaderViewHolder headerViewHolder = (HeaderViewHolder) holder;
                final EFDataSet dataSet = (EFDataSet) getItem(position);
                headerViewHolder.textView.setText(dataSet.getTableName());
                headerViewHolder.itemView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        Log.i("--","点击的位置：" + position);
                    }
                });
                //处理header CheckBox
                if (shoppingShow.isShowCheckBox()){
                    headerViewHolder.checkBox.setVisibility(View.VISIBLE);
                }else {
                    headerViewHolder.checkBox.setVisibility(View.GONE);
                }
                headerViewHolder.checkBox.setChecked(ShoppingCarDataManager.isDataSetChecked(dataSet));
                headerViewHolder.checkBox.setDataSetID(shoppingShow.getDataSetID());
                headerViewHolder.checkBox.setDataSetComponent(shoppingShow.getDataSetComponent());
                headerViewHolder.checkBox.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        ShoppingCarDataManager.setDataSetChecked(dataSet,headerViewHolder.checkBox.isChecked());
                        notifyDataSetChanged();
                    }
                });
                break;
            //如果是子项类型，处理子项的布局
            case TYPE_ITEM:
                final ItemViewHolder itemViewHolder = (ItemViewHolder) holder;
                // 绑定数据
                final EFRowSet rowSet = (EFRowSet) getItem(position);
                List<DataComponent> columnList = shoppingShow.getColumnModel().getChildren();
                for (int i=0 ; i<columnList.size() ; i++){
                    final Column column = (Column) columnList.get(i);
                    if ("name".equals(column.getComponentType())){
                        itemViewHolder.name.setDataSetID(column.getDataSetID());
                        itemViewHolder.name.setDataSetColID(column.getDataSetColID());
                        itemViewHolder.name.setDataSetComponent(shoppingShow.getDataSetComponent());
                        itemViewHolder.name.dataChanged(rowSet.getDataSet());
                    }else if ("description".equals(column.getComponentType())){
                        itemViewHolder.description.setDataSetID(column.getDataSetID());
                        itemViewHolder.description.setDataSetColID(column.getDataSetColID());
                        itemViewHolder.description.setVisibility(column.isVisible()?View.VISIBLE:View.GONE);
                        itemViewHolder.description.setDataSetComponent(shoppingShow.getDataSetComponent());
                        itemViewHolder.description.dataChanged(rowSet.getDataSet());
                    }else if ("unit".equals(column.getComponentType())){
                        itemViewHolder.unit.setDataSetID(column.getDataSetID());
                        itemViewHolder.unit.setDataSetColID(column.getDataSetColID());
                        itemViewHolder.unit.setDataSetComponent(shoppingShow.getDataSetComponent());
                        itemViewHolder.unit.setEditMask("吨:吨;升:升;千克:千克;");
                        itemViewHolder.unit.creationComplete();
                        itemViewHolder.unit.setEditable(column.isEditable());
                        itemViewHolder.unit.dataChanged(rowSet.getDataSet());
                    }else if ("icon".equals(column.getComponentType())){
                        itemViewHolder.icon.setDataSetID(column.getDataSetID());
                        itemViewHolder.icon.setDataSetColID(column.getDataSetColID());
                        itemViewHolder.icon.setDefaultImageLoadMode(column.getDefaultImageLoadMode());
                        itemViewHolder.icon.setImageUrlPrefix(column.getImageUrlPrefix());
                        itemViewHolder.icon.setDataSetComponent(shoppingShow.getDataSetComponent());
                        itemViewHolder.icon.dataChanged(rowSet.getDataSet());
                    }else if ("price".equals(column.getComponentType())){
                        if (column.isVisible()){
                            itemViewHolder.priceContainer.setVisibility(View.VISIBLE);
                        }else {
                            itemViewHolder.priceContainer.setVisibility(View.GONE);
                        }
                        //默认text
                        itemViewHolder.price.setOriginalText(column.getHeaderText());
                        //设置文本类型
                        itemViewHolder.price.setTextType(FormTextInput.TEXT_TYPE_NUMBER);
                        //设置精度
                        itemViewHolder.price.setDegree(column.getDegree());
                        itemViewHolder.price.setDataSetID(column.getDataSetID());
                        itemViewHolder.price.setDataSetColID(column.getDataSetColID());
                        itemViewHolder.price.setDataSetComponent(shoppingShow.getDataSetComponent());
                        itemViewHolder.price.dataChanged(rowSet.getDataSet());
                        itemViewHolder.price.setEditable(column.isEditable());

                    }else if ("count".equals(column.getComponentType())){
                        //默认text
                        itemViewHolder.count.setOriginalText(column.getHeaderText());
                        //设置文本类型
                        itemViewHolder.count.setTextType(FormTextInput.TEXT_TYPE_NUMBER);
                        //设置精度
                        itemViewHolder.count.setDegree(column.getDegree());
                        itemViewHolder.count.setDataSetID(column.getDataSetID());
                        itemViewHolder.count.setDataSetColID(column.getDataSetColID());
                        itemViewHolder.count.setDataSetComponent(shoppingShow.getDataSetComponent());
                        itemViewHolder.count.dataChanged(rowSet.getDataSet());
                        itemViewHolder.count.setEditable(column.isEditable());
                    }else if ("checkBox".equals(column.getComponentType())){
                        if (shoppingShow.isShowCheckBox()){
                            itemViewHolder.checkBox.setVisibility(View.VISIBLE);
                        }else {
                            itemViewHolder.checkBox.setVisibility(View.GONE);
                        }
                        itemViewHolder.checkBox.setDataSetID(column.getDataSetID());
                        itemViewHolder.checkBox.setDataSetColID(column.getDataSetColID());
                        itemViewHolder.checkBox.setDataSetComponent(shoppingShow.getDataSetComponent());
                        itemViewHolder.checkBox.dataChanged(rowSet.getDataSet());
                        itemViewHolder.checkBox.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                notifyDataSetChanged();
                            }
                        });
                    }
                }

                itemViewHolder.deleteTextView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        //删除dataSet数据
                        int position = holder.getAdapterPosition();
                        Object object = getItem(position);
                        if (object instanceof EFRowSet){
                            EFRowSet efRowSet = (EFRowSet) object;
                            EFDataSet efDataSet = efRowSet.getDataSet();
                            if (efDataSet == null) return;
                            ESPRowSet removedRowSet = efDataSet.removeRowSet(efRowSet);
                            if (removedRowSet != null){
                                notifyItemRemoved(position);
//                                shoppingShow.getShoppingCarFormModel().dataSetChanged(new DataSetEvent(efDataSet,DataSetEvent.DELETE));
                            }
                            if (efDataSet.getRowSetArray() == null || efDataSet.getRowSetArray().size() == 0){
                                int dataSetPosition = ShoppingCarDataManager.getPosition(dataSetList,efDataSet);
                                notifyItemRemoved(dataSetPosition);
                                dataSetList.remove(efDataSet);
                            }

                            ArcMenu arcMenu = shoppingShow.getArcMenu();
                            EFArcMenuSuperScriptItem arcMenuItem = (EFArcMenuSuperScriptItem) arcMenu.getItem(0);
                            arcMenuItem.superscriptAddNumber(-1);

                        }
                    }
                });

                itemViewHolder.itemView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        Log.i("--","点击的位置：" + position);
                    }
                });
                break;
        }

    }

    /**
     * 获取Item的类别，也即确定是子项还是标题项
     */
    @Override
    public int getItemViewType(int position) {
        // 异常情况处理
        if (null == dataSetList || position < 0 || position > getItemCount()) {
            return TYPE_ITEM;
        }
        // 初始遍历位置
        int categoryFirstIndex = 0;
        // 遍历实体类集合
        for (EFDataSet dataSet : dataSetList) {
            int size = ShoppingCarDataManager.getItemCount(dataSet);
            // 在当前分类中的索引值
            int categoryIndex = position - categoryFirstIndex;
            // 如果是首项返回标题类型
            if (categoryIndex == 0) {
                return TYPE_CATEGORY_ITEM;
            }
            //如果是子项返回子项类型
            if (categoryIndex > 0  && categoryIndex < size - 1) {
                return TYPE_ITEM;
            }
            categoryFirstIndex += size;
        }
        return TYPE_ITEM;
    }



    @Override
    public long getItemId(int position) {
        return position;
    }

    /**
     * 获取所有分类的Item的总数
     */
    @Override
    public int getItemCount() {
        int count = 0;
        if (null != dataSetList) {
            // 所有分类中item的总和是ListVIew Item的总个数
            for (EFDataSet dataSet : dataSetList) {
                count += ShoppingCarDataManager.getItemCount(dataSet);
            }
        }
        return count;
    }


    @Override
    public void onAttachedToRecyclerView(RecyclerView recyclerView) {
        super.onAttachedToRecyclerView(recyclerView);

        mRecyclerView = recyclerView;
        if (shoppingShow.isShowDeleteButton()){
            mRecyclerView.addOnItemTouchListener(new ItemSlideHelper(mRecyclerView.getContext(), this));
        }else {
        }

    }

    @Override
    public int getHorizontalRange(RecyclerView.ViewHolder holder) {
        View view = holder.itemView.findViewById(R.id.swipe_container);
        if (view != null){
            return view.getLayoutParams().width;
        }
        return 0;
    }

    @Override
    public RecyclerView.ViewHolder getChildViewHolder(View childView) {
        return mRecyclerView.getChildViewHolder(childView);
    }

    @Override
    public View findTargetView(float x, float y) {
        return mRecyclerView.findChildViewUnder(x,y);
    }

    public void clearShoppingCar(){
        if (dataSetList == null) return;
        dataSetList.clear();
        notifyDataSetChanged();
        shoppingShow.getShoppingCarFormModel().getFormDataModel().setDataSetMap(new HashMap<String, EFDataSet>());
        //清空arcMenu角标
        ArcMenu arcMenu = shoppingShow.getArcMenu();
        EFArcMenuSuperScriptItem arcMenuItem = (EFArcMenuSuperScriptItem) arcMenu.getItem(0);
        arcMenuItem.clearSuperscriptNumber();
//        shoppingShow.getShoppingCarFormModel().dataSetChanged(new DataSetEvent(efDataSet,DataSetEvent.DELETE));
    }

    /**
     * 标题 ViewHolder
     */
    private class HeaderViewHolder extends RecyclerView.ViewHolder{
        FormCheckBox checkBox;
        TextView textView;
        public HeaderViewHolder(View itemView) {
            super(itemView);
            checkBox = (FormCheckBox) itemView.findViewById(R.id.header_checkBox);
            checkBox.creationComplete();
            textView = (TextView) itemView.findViewById(R.id.header_tv);
        }
    }

    /**
     * 产品条目 ViewHolder
     */
    private class ItemViewHolder extends RecyclerView.ViewHolder{
        FormCheckBox checkBox;
        FormLabel name;
        FormLabel description;
        FormTextInput count;
        FormTextInput price;
        LinearLayout priceContainer;
        FormSpinner unit;
        FormImage icon;

        TextView deleteTextView;
        LinearLayout itemContainer;
        public ItemViewHolder(View itemView) {
            super(itemView);
            checkBox = (FormCheckBox) itemView.findViewById(R.id.checkBox);
            checkBox.creationComplete();
            name = (FormLabel) itemView.findViewById(R.id.name);
            name.creationComplete();
            description = (FormLabel) itemView.findViewById(R.id.description);
            description.creationComplete();
            count = (FormTextInput) itemView.findViewById(R.id.count);
            count.creationComplete();

            price = (FormTextInput) itemView.findViewById(R.id.price);
            price.creationComplete();

            priceContainer = (LinearLayout) itemView.findViewById(R.id.price_container);
            price.creationComplete();
            unit = (FormSpinner) itemView.findViewById(R.id.unit);
            unit.creationComplete();
            icon = (FormImage) itemView.findViewById(R.id.imageView);
            icon.creationComplete();

            deleteTextView = (TextView) itemView.findViewById(R.id.tv_delete);
            itemContainer = (LinearLayout) itemView.findViewById(R.id.item_container);
        }
    }
}